import { defineStore } from 'pinia'
import { Names } from './storeNamespace'
import { RouteRecordRaw } from "vue-router"
import Layout from '@/layout/Index.vue'
import { Result } from '@/http/request'
import { getAdminMenuApi } from '@/http/api/menu'
import router from '@/router'
const modules = import.meta.glob('../views/**/*.vue')

interface IMenuStore {
    collapse: boolean,
    isGetMenuList: boolean,
    menuList: any,
    adminAuth: Array<string>
}

const menuListStorage = [
    {
        path: '/home',
        name: 'home',
        component: 'Layout',
        meta: {
            title: '后台首页',
            icon: 'HomeFilled',
            is_menu: true
        },
        children: []
    }
]

const menuStore = (): IMenuStore => {
    return {
        collapse: false,
        isGetMenuList: false,
        menuList: menuListStorage,
        adminAuth: []
    }
}


export const useMenuStore = defineStore(Names.Menu, {
    state: () => menuStore(),
    persist: {
        enabled: true,
        strategies: [
            {
                storage: sessionStorage,
                paths: ['collapse',]
            }
        ]
    },
    getters: {
        getCollapse: (store) => store.collapse,
        getIsGetMenuList: (store) => store.isGetMenuList,
        getMenuList: (store) => store.menuList,
        getAdminAuth: (store) => store.adminAuth
    },
    actions: {
        getMenuListAndAuth(): Promise<Result> {
            return new Promise((resolve) => {
                getAdminMenuApi().then((res) => {
                    let accessedRoutes
                    if (res && res.code == 200) {
                        accessedRoutes = filterAsyncRoutes(res.data.menu_list)
                        this.menuList = menuListStorage.concat(accessedRoutes)
                        this.adminAuth = res.data.auth
                        this.isGetMenuList = true
                    }
                    resolve(res)
                })
            })
        }
    }
})

// 动态生成路由
export function filterAsyncRoutes(routes: Array<RouteRecordRaw>) {
    const res: Array<RouteRecordRaw> = []
    routes.forEach((route: any) => {
        const temp = { ...route }
        const component = temp.component
        if (component) {
            if (component == 'Layout') {
                temp.component = Layout
            } else {
                temp.component = modules[`../views${component}.vue`]
            }
        }
        if (temp.children && temp.children.length > 0) {
            temp.children = filterAsyncRoutes(temp.children)
        }
        router.addRoute(temp)
        res.push(temp)
    })
    return res
}